package com.sctvcloud.qingchuan.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Cache;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.base.BaseAccountActivity;
import com.sctvcloud.qingchuan.beans.AccountBean;
import com.sctvcloud.qingchuan.beans.AccountTabBean;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.adapter.AccountDetailPagerAdapter;
import com.sctvcloud.qingchuan.ui.dialog.AccountEditWarningFragment;
import com.sctvcloud.qingchuan.ui.dialog.AccountShareFragment;
import com.sctvcloud.qingchuan.ui.dialog.AccountWarningFragment;
import com.sctvcloud.qingchuan.ui.fragment.AccountDetailNewsFragment;
import com.sctvcloud.qingchuan.ui.utils.DataUtils;
import com.sctvcloud.qingchuan.ui.utils.GlideCircleTransform;
import com.sctvcloud.qingchuan.ui.utils.GlideUtil;
import com.sctvcloud.qingchuan.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 公众号详情页
 */
public class AccountDetailActivity extends BaseAccountActivity implements OnTabSelectListener {
    @BindView(R.id.account_top_avatar)
    protected ImageView accountTopAvatar;
    @BindView(R.id.account_top_name)
    protected CustomFontTextView accountTopName;
    @BindView(R.id.account_top_subscribe)
    protected ImageView accountTopSubscribe;

    @BindView(R.id.account_avatar)
    protected ImageView accountAvatar;
    @BindView(R.id.account_name)
    protected CustomFontTextView accountName;
    @BindView(R.id.account_subscribe)
    protected ImageView accountSubscribe;


    @BindView(R.id.account_publish_num)
    protected CustomFontTextView accountPublishNum;
    @BindView(R.id.account_attention_num)
    protected CustomFontTextView accountAttentionNum;
    @BindView(R.id.account_intro)
    protected CustomFontTextView accountIntro;

    @BindView(R.id.app_bar_layout)
    protected AppBarLayout appBarLayout;

    @BindView(R.id.account_tablay)
    protected SlidingTabLayout accountTabLay;
    @BindView(R.id.account_content_vp)
    protected ViewPager accountContentVp;
    private AccountShareFragment shareFragment;
    private AccountWarningFragment warningFragment;
    private AccountEditWarningFragment warningEditFragment;
    private Handler handler;
    private boolean mIsLoading = false;
    public static final String ACCOUNT_ID = "account_id";
    private AccountBean mAccountDetailBean;
    private GlideCircleTransform circleTransform;
    private AccountDetailPagerAdapter adapter;
    private String accointId = "";
    private int currentIndex = 0;
    //页面滑动位移
    private int currentOffset = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_account_detail);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        accointId = getIntent().getStringExtra(ACCOUNT_ID);
        accountTopAvatar.setVisibility(View.GONE);
        accountTopName.setVisibility(View.GONE);
        accountTopSubscribe.setVisibility(View.GONE);

        circleTransform = new GlideCircleTransform(this);
        getAccountDetail();
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                double pe = ((double) Math.abs(verticalOffset)) / appBarLayout.getTotalScrollRange();
                int pp = (int) (pe * 100);
                currentOffset = Math.abs(verticalOffset);
                if (pp >= 100 || Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
                    accountTopAvatar.setVisibility(View.VISIBLE);
                    accountTopName.setVisibility(View.VISIBLE);
                    accountTopSubscribe.setVisibility(View.VISIBLE);
                } else {
                    accountTopAvatar.setVisibility(View.GONE);
                    accountTopName.setVisibility(View.GONE);
                    accountTopSubscribe.setVisibility(View.GONE);
                }
                initFragmentRefreshStatus();
            }
        });
    }


    /**
     * 请求公众号详情数据
     */
    private void getAccountDetail() {
        String accessToken = "";
        if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getAccountUser()) {
            accessToken = UserManager.getInstance().getUser().getAccountUser().getAccess_token();
        }
        mIsLoading = true;
        Map<String, String> formMaildata = new HashMap<>();
        formMaildata.put("tenantId", Constances.TENANT_ID);
        formMaildata.put("hisUserId", accointId);

        Map<String, RequestBody> bodyMap = DataUtils.generateRequestBody(formMaildata);
        showProgress("正在加载...");
        NetUtils.getNetAdapter().getAccountInfoString(getOwnerName(), accessToken, bodyMap, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSucStr(String news) {
                if (!TextUtils.isEmpty(news)) {
                    try {
                        mAccountDetailBean = gson.fromJson(news, AccountBean.class);
                        if (mAccountDetailBean != null) {
                            initDetail(mAccountDetailBean);
                            initTab();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    onError(null, "数据异常");
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);
            }

            @Override
            public void onEnd() {
                closeProgress();
                mIsLoading = false;
            }
        });
    }

    /**
     * 请求公众号详情数据
     */
    private void refreshAccountDetail() {
        String accessToken = "";
        if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getAccountUser()) {
            accessToken = UserManager.getInstance().getUser().getAccountUser().getAccess_token();
        }
        mIsLoading = true;
        Map<String, String> formMaildata = new HashMap<>();
        formMaildata.put("tenantId", Constances.TENANT_ID);
        formMaildata.put("hisUserId", accointId);

        Map<String, RequestBody> bodyMap = DataUtils.generateRequestBody(formMaildata);
        NetUtils.getNetAdapter().getAccountInfoString(getOwnerName(), accessToken, bodyMap, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSucStr(String news) {
                if (!TextUtils.isEmpty(news)) {
                    try {
                        mAccountDetailBean = gson.fromJson(news, AccountBean.class);
                        if (mAccountDetailBean != null) {
                            initDetail(mAccountDetailBean);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    onError(null, "数据异常");
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);
            }

            @Override
            public void onEnd() {
                mIsLoading = false;
            }
        });
    }

    /**
     * 初始化公众号信息
     *
     * @param detail
     */
    private void initDetail(AccountBean detail) {
        accountTopAvatar.setVisibility(View.GONE);
        accountTopName.setVisibility(View.GONE);
        accountTopSubscribe.setVisibility(View.GONE);

        GlideUtil.getDynamicGlid(this, detail.getUserImage(), true).diskCacheStrategy(DiskCacheStrategy.NONE).transform(circleTransform).into(accountTopAvatar);
        GlideUtil.getDynamicGlid(this, detail.getUserImage(), true).diskCacheStrategy(DiskCacheStrategy.NONE).transform(circleTransform).into(accountAvatar);
        accountTopName.setText(detail.getUserNickName());
        accountName.setText(detail.getUserNickName());
        if (detail.isHasAttention()) {
            accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
            accountTopSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
        } else {
            accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
            accountTopSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
        }
        accountPublishNum.setText("" + detail.getDynamicNumber());
        accountAttentionNum.setText("" + detail.getFansNumber());
        accountIntro.setText(detail.getDescription());


    }

    /**
     * 加载公众号新闻tab
     */
    private void initTab() {
        List<AccountTabBean> tabList = new ArrayList<>();
        tabList.add(new AccountTabBean(accointId, 1, "文章", AccountDetailPagerAdapter.TYPE_NORMAL_NEWS));
        tabList.add(new AccountTabBean(accointId, 2, "组图", AccountDetailPagerAdapter.TYPE_IMAGES_NEWS));
        tabList.add(new AccountTabBean(accointId, 3, "视频", AccountDetailPagerAdapter.TYPE_VIDEO_NEWS));
        if (adapter == null) {
            adapter = new AccountDetailPagerAdapter(getSupportFragmentManager(), tabList);
            accountContentVp.setAdapter(adapter);
            accountContentVp.setOffscreenPageLimit(1);
            accountTabLay.setViewPager(accountContentVp);
            accountTabLay.setChangeSize(true);
        } else {
            adapter.setData(tabList);
        }
        adapter.notifyDataSetChanged();
        accountTabLay.setCurrentTab(0);
        accountTabLay.setTabPaddingPx(getResources().getDimension(R.dimen.tab_home_padding));
        accountTabLay.setOnTabSelectListener(this);
    }


    @Override
    public void onTabSelect(int position) {
        currentIndex = position;
        initFragmentRefreshStatus();
    }

    @Override
    public void onTabReselect(int position) {

    }

    @Override
    public void onTabScrollTo(int position) {

    }

    @OnClick(value = {R.id.account_detail_back, R.id.account_top_subscribe, R.id.account_subscribe, R.id.account_detail_set})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.account_detail_back:
                onBackPressed();
                break;
            case R.id.account_top_subscribe:
            case R.id.account_subscribe:
                //TODO 关注、取消关注
                setResult(RESULT_OK);
                if (null != UserManager.getInstance().getUser()) {
                    toAttentionClick(mAccountDetailBean.isHasAttention());
                }else{
                    toLogin();
                }
                break;
            case R.id.account_detail_set:
                //TODO 分享
                accountShare();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                refreshAccountDetail();
                setResult(RESULT_OK);
            }
        }
    }

    /**
     * 根据滑动位移设置列表是否可以下拉刷新
     */
    private void initFragmentRefreshStatus() {
        if (null != adapter) {
            AccountDetailNewsFragment fragment = (AccountDetailNewsFragment) adapter.getFragmentByPos(currentIndex);
            if (currentOffset == 0) {
                fragment.setRefreshLayoutRefreshEnable(true);
            } else {
                fragment.setRefreshLayoutRefreshEnable(false);
            }
        }
    }

    /**
     * 处理 关注或取消关注
     *
     * @param isAttention
     */
    private void toAttentionClick(boolean isAttention) {
        if (isAttention) {
            toUnAttentionAccount(mAccountDetailBean.getUserId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {

                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {
                    mAccountDetailBean.setHasAttention(!mAccountDetailBean.isHasAttention());
                    if (mAccountDetailBean.isHasAttention()) {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                        accountTopSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                    } else {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                        accountTopSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                    }
                }
            });
        } else {
            toAttentionAccount(mAccountDetailBean.getUserId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {
                    mAccountDetailBean.setHasAttention(!mAccountDetailBean.isHasAttention());
                    if (mAccountDetailBean.isHasAttention()) {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                        accountTopSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                    } else {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                        accountTopSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                    }
                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {

                }
            });
        }
    }

    /**
     * 选择分享
     */
    private void accountShare() {
        if (null != mAccountDetailBean && !TextUtils.isEmpty(mAccountDetailBean.getPersonHomePageUrl())) {
            shareFragment = new AccountShareFragment(mAccountDetailBean);

            shareFragment.setOnAccountShareFragmentClickListener(new AccountShareFragment.OnAccountShareFragmentWarningClickListener() {
                @Override
                public void onClick() {
                    //TODO 举报
                    Warning();
                }
            });
            FragmentManager fm = getSupportFragmentManager();
            shareFragment.show(fm, SHARE_TAG);
            fm.executePendingTransactions();
        }
    }


    /**
     * 选择举报
     */
    private void Warning() {
        warningFragment = new AccountWarningFragment();
        warningFragment.setConfirmListener(new AccountWarningFragment.OnWarningConfirmListener() {
            @Override
            public void OnWarningConfirm(String title, boolean isMore) {
                if (isMore) {
                    ToEditWarning();
                } else {
                    toSendWarning(title);
                }
            }
        });
        FragmentManager fm = getSupportFragmentManager();
        warningFragment.show(fm, SHARE_TAG);
        fm.executePendingTransactions();
    }

    /**
     * 编辑吐槽内容
     */
    private void ToEditWarning() {
        warningEditFragment = new AccountEditWarningFragment();
        warningEditFragment.setSendListener(new AccountEditWarningFragment.OnWarningSendListener() {
            @Override
            public void OnWarningSend(String editWarning) {
                toSendWarning(editWarning);
            }
        });
        FragmentManager fm = getSupportFragmentManager();
        warningEditFragment.show(fm, SHARE_TAG);
        fm.executePendingTransactions();
    }

    /**
     * 提交吐槽、举报
     */
    private void toSendWarning(final String warningContent) {
        closeAllDia();
        showProgress("正在提交...");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                toast("提交成功");
                closeProgress();
            }
        }, 1000);

    }

    private void closeAllDia() {
        if (null != shareFragment) {
            shareFragment.dismissAllowingStateLoss();
        }
        if (null != warningFragment) {
            warningFragment.dismissAllowingStateLoss();
        }
        if (null != warningEditFragment) {
            warningEditFragment.dismissAllowingStateLoss();
        }
    }
}
